$(function () {
    var _search = parseSearch(), selected = {};
    var config = {
        detail: '/ladingBill/get?id=' + _search.id,
        getPurchaseOrderBill: '/purchaseOrderBill/query?keyword=send&goodsId=',

    }, orders = {}, bills = {};
    $.get(config.detail, function (res) {
        if (res.code == 200) {
            var $tbody = $('.table-batch tbody');
            var list = {};
            res.data.ladingBillDetail.map(function (item) {
                var obj = {};
                if (list.billId) {
                    var obj = list.billId;
                    obj.number = floatTool.add(obj.number, item.number);
                } else {
                    obj =
                    {
                        id: item.id,
                        billBatch: item.billBatch,
                        number: item.number,
                        billId: item.billId
                    }
                }
                list[item.id] = obj;
            });
            $('.total').html('提货单数量：' + res.data.ladingBill.numberThisTime + ' 吨');
            $tbody.html(ejs.render($('#item').html(), {list: _.values(list)}));
            $(ejs.render($('#summary').html(), res.data.ladingBill)).insertAfter('#summary-title');
            onClick($('.data-select-selected'), function (item) {
                var $id = $(this).data('id');
                var url = config.getPurchaseOrderBill + res.data.ladingBill.goodsId;
                if (res.data.ladingBill.type == 0 || res.data.ladingBill.type == 2) {
                    url += '&checkStatus=1';
                } else {
                    url += '&checkStatus=1&numberReceive=1'
                }
                var $json = $(this).data('id');
                $.when(window.parent.getDataByUrl(url, 'getPurchaseOrderBill' + Math.random()))
                    .then(function (res1) {
                        var $modal = _alert({
                            width: '95%',
                            okbtn: '替换',
                            title: '选择替换批号:',
                            body: ejs.render($('#form-select').html(), {
                                purchase: res1,
                                selected: selected,
                                _id: $id.billId
                            }),
                            show: function () {
                                initTips(res.data.ladingBill.numberThisTime, 0);
                                $('.modal-body').addClass('min-height250')
                            },
                            shown: function () {
                                $('.modal-body input[type=checkbox]').change(function (index, item) {
                                    if ($(this).is(":checked")) {
                                        var $json_ = $(this).data('json');
                                        if ($json_.type == 0) {
                                            var remain = $json_.number;
                                            if (remain < parseFloat($json.number)) {
                                                return alert('所选提货单库存数量不足!');
                                            } else {
                                                $(this).closest('tr').find('input.form-inline').val($json.number);
                                                getSelectedBatch(res.data.ladingBill.numberThisTime);
                                            }
                                        } else {
                                            var remain = floatTool.subtract($json_.numberReceive, $json.numberSending);
                                            remain = floatTool.subtract(remain, $json.numberSended);
                                            if (remain < parseFloat($json.number)) {
                                                return alert('所选提货单库存数量不足!');
                                            } else {
                                                $(this).closest('tr').find('input.form-inline').val($json.number);
                                                getSelectedBatch(res.data.ladingBill.numberThisTime);
                                            }
                                        }
                                    } else {
                                        $(this).closest('tr').find('input.form-inline').val(0);
                                        getSelectedBatch(res.data.ladingBill.numberThisTime);
                                    }
                                });
                                getSelectedBatch(res.data.ladingBill.numberThisTime);
                            },
                            okHide: function (e) {
                                selected = {};
                                var store = {};
                                if ($('.modal input[type=checkbox]:checked').length != 1) {
                                    return "请选择一个批号进行替换";
                                }
                                $.post('/ladingBill/replace/' + $json.id,
                                    {billId: $('.modal input[type=checkbox]:checked').data('json').id},
                                    function (res) {
                                        console.log(res);
                                        if (res.code == 200) {
                                            // $modal.modal('hide');
                                            alert('更换批号成功');
                                            window.location = window.location;
                                        } else {
                                            fnFail(res.error);
                                        }
                                    });

                                return true;
                            },
                            hasfoot: true,
                        });
                    })
                    .fail(function (e) {
                        fnFail(e);
                    })
            })
        } else {
            fnFail(res.error);
        }
    });


    function getSelectedBatch(calculate) {
        var total = 0, total_ = calculate;
        $('.modal input[type=checkbox]:checked').each(function (index, item) {
            var $json = $(this).data('json'), tmp_ = 0;
            if ($json.numberReceive > 0) {
                var tmp = floatTool.subtract($json.numberReceive, $json.numberSended);//　扣减批号已发货数量
                tmp_ = floatTool.subtract(tmp, $json.numberSending);　// 扣减批号发货中数量
            } else {
                tmp_ = $json.number;
            }
            var totalTmp = floatTool.add(total, tmp_);
            if (totalTmp == total_) {
                $(this).closest('tr').find('input[type=text]').val(floatTool.subtract(total_, total))
            } else if (totalTmp > total_) {
                if (total_ >= total) {
                    $(this).closest('tr').find('input[type=text]').val(floatTool.subtract(total_, total))
                } else {
                    $(this).closest('tr').find('input[type=text]').val(0)
                }
            } else if (totalTmp < total_) {
                $(this).closest('tr').find('input[type=text]').val(tmp_)
            }
            total = totalTmp;
        });
        $('.modal input[type=checkbox]').not(":checked").each(function (index, item) {
            $(this).closest('tr').find('input[type=text]').val(0);
        });
        initTips(calculate, total);
        return total;
    }

    function initTips(total, total_) {
        if (!$('.modal-header .modal-title .pull-right').length) {
            $('.modal-header .modal-title').append('<span class="pull-right" style="margin-right: 150px;">合计发货数量：' + total + ' 吨，已选批号库存：' + total_ + ' 吨</span>');
        } else {
            $('.modal-header .modal-title .pull-right').html('提单数量：' + total + ' 吨，已选批号数量：' + total_ + ' 吨')
        }
    }

    $('#form-send').submit(function (e) {
        e.stopPropagation();
        e.preventDefault();
        var $formStr = $('#form-send').serialize();
        var form = parseSearch($formStr);
        var hasUnpay = false;
        form.numberThisTime = 0;
        if (form.orderNumbers) {
            form.orderNumbers.split(',').map(function (item) {
                form.numberThisTime = floatTool.add(parseFloat(item), form.numberThisTime);
            })
        } else {
            return fnFail("请选择批号!")
        }

        $.post(config.create_labing_bill, form, function (xhr, data) {
            if (xhr.code == 200) {
                fnSuccess('发货成功!');
            } else {
                if (hasUnpay && xhr.error.indexOf('无权操作') > -1) {
                    fnFail("货款不足，请补足货款再操作!")
                } else {
                    fnFail(xhr.error)
                }
            }
        });
        return false;
    });

});